<template>
    <div class="app-container">
      <el-card v-loading="loading" class="exam-card">
        <template #header>
          <div class="card-header">
            <span class="title">{{ examInfo?.examName }}</span>
            <div class="exam-info">
              <span>剩余时间：{{ formatTime(remainingTime) }}</span>
              <el-button type="primary" @click="handleSubmit">提交试卷</el-button>
            </div>
          </div>
        </template>
  
        <div v-for="(question, index) in examInfo?.questionVos" :key="question.questionId" class="question-item">
          <div class="question-header">
            <span class="question-number">{{ index + 1 }}.</span>
            <span class="question-type">{{ getQuestionTypeName(question.questionType) }}</span>
            <span class="question-score">({{ question.score }}分)</span>
          </div>
          
          <div class="question-content">{{ question.questionContent }}</div>
          
          <!-- 单选题 -->
          <div v-if="question.questionType === 'single-choice'" class="question-options">
            <el-radio-group v-model="answers[question.questionId]">
              <el-radio 
                v-for="option in question.options" 
                :key="option.id"
                :label="option.optionLetter"
              >
                {{ option.optionLetter }}. {{ option.optionContent }}
              </el-radio>
            </el-radio-group>
          </div>
  
          <!-- 多选题 -->
          <div v-if="question.questionType === 'multiple-choice'" class="question-options">
            <el-checkbox-group v-model="answers[question.questionId]">
              <el-checkbox 
                v-for="option in question.options" 
                :key="option.id"
                :label="option.optionLetter"
              >
                {{ option.optionLetter }}. {{ option.optionContent }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
  
          <!-- 填空题 -->
          <div v-if="question.questionType === 'blank-filling'" class="question-answer">
            <el-input 
              v-model="answers[question.questionId]" 
              type="textarea" 
              :rows="3"
              placeholder="请输入答案"
            />
          </div>
  
          <!-- 编程题 -->
          <div v-if="question.questionType === 'coding'" class="question-answer">
            <el-input 
              v-model="answers[question.questionId]" 
              type="textarea" 
              :rows="10"
              placeholder="请输入代码"
            />
          </div>
  
          <!-- 显示正确答案（如果有） -->
          <div v-if="question.rightAnswer" class="correct-answer">
            <el-tag type="success">正确答案：{{ question.rightAnswer }}</el-tag>
          </div>
        </div>
      </el-card>
    </div>
  </template>
  
  <script setup name="ExamPage">
  import { ref, onMounted, onUnmounted } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { myExamInfo,submitDataApi } from "@/api/business/exam";
  import { ElMessage } from 'element-plus';
  
  const route = useRoute();
  const router = useRouter();
  const loading = ref(true);
  const examInfo = ref(null);
  const answers = ref({});
  const remainingTime = ref(0);
  const startTime = ref(null);
  let timer = null;
  
  // 题目类型映射
  const questionTypeMap = {
    'single-choice': '单选题',
    'multiple-choice': '多选题',
    'blank-filling': '填空题',
    'coding': '编程题'
  };
  
  // 获取题目类型名称
  function getQuestionTypeName(type) {
    return questionTypeMap[type] || type;
  }
  
  // 格式化时间
  function formatTime(seconds) {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = seconds % 60;
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  }
  
  // 获取考试信息
  function getExamInfo() {
    const examId = route.query.id;
    console.log(examId,examId)
    if (!examId) {
      ElMessage.error('考试ID不存在');
      router.push('/business/myexam');
      return;
    }

    loading.value = true;
    myExamInfo(examId).then(response => {
      if (response.code === 200) {
        examInfo.value = response.data;
        // Set start time when exam info is loaded
        startTime.value = new Date().toISOString();
        
        // 初始化答案对象并填充已有答案
        examInfo.value.questionVos.forEach(question => {
          if (question.answer) {
            if (question.questionType === 'multiple-choice') {
              // 多选题答案格式为 "A,B,C"
              answers.value[question.questionId] = question.answer.split(',');
            } else {
              // 其他类型直接使用答案
              answers.value[question.questionId] = question.answer;
            }
          } else {
            // 没有答案时初始化空值
            if (question.questionType === 'multiple-choice') {
              answers.value[question.questionId] = [];
            } else {
              answers.value[question.questionId] = '';
            }
          }
        });
        
        // 计算剩余时间
        const endTime = new Date(examInfo.value.endTime);
        const now = new Date();
        const timeDiff = Math.floor((endTime - now) / 1000); // 转换为秒
        
        if (timeDiff <= 0) {
          ElMessage.warning('考试已结束');
          router.push('/business/myexam');
          return;
        }
        
        remainingTime.value = timeDiff;
        startTimer();
      } else {
        ElMessage.error(response.msg || '获取考试信息失败');
      }
      loading.value = false;
    }).catch(() => {
      loading.value = false;
      router.push('/business/myexam');
    });
  }
  
  // 开始计时器
  function startTimer() {
    timer = setInterval(() => {
      if (remainingTime.value > 0) {
        remainingTime.value--;
      } else {
        clearInterval(timer);
        handleSubmit();
      }
    }, 1000);
  }
  
  // 提交试卷
  function handleSubmit() {
    if (timer) {
      clearInterval(timer);
    }
    
    // 构建提交数据
    const submitData = {
      examId: examInfo.value.examId,
      startTime: startTime.value,
      endTime: new Date().toISOString(),
      answers: Object.entries(answers.value).map(([questionId, answer]) => ({
        questionId: parseInt(questionId),
        studentAnswerContent: Array.isArray(answer) ? answer.join(',') : answer
      }))
    };
    
    submitDataApi(submitData).then(response => {
        if (response.code === 200) {
        console.log('response',response);
        ElMessage.success('试卷提交成功');
        router.push('/question/myexam');}
    })
  }
  
  onMounted(() => {
    getExamInfo();
  });
  
  onUnmounted(() => {
    if (timer) {
      clearInterval(timer);
    }
  });
  </script>
  
  <style scoped>
  .exam-card {
    margin: 20px;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .title {
    font-size: 20px;
    font-weight: bold;
  }
  
  .exam-info {
    display: flex;
    align-items: center;
    gap: 20px;
  }
  
  .question-item {
    margin-bottom: 30px;
    padding: 20px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
  }
  
  .question-header {
    margin-bottom: 15px;
    font-weight: bold;
    display: flex;
    align-items: center;
    gap: 10px;
  }
  
  .question-number {
    font-size: 16px;
  }
  
  .question-type {
    color: #409EFF;
  }
  
  .question-score {
    color: #67C23A;
  }
  
  .question-difficulty {
    color: #909399;
  }
  
  .question-content {
    margin-bottom: 15px;
    line-height: 1.5;
  }
  
  .question-options {
    margin: 15px 0;
  }
  
  .question-answer {
    margin: 15px 0;
  }
  
  .correct-answer {
    margin-top: 15px;
  }
  
  :deep(.el-radio) {
    display: block;
    margin: 10px 0;
  }
  
  :deep(.el-checkbox) {
    display: block;
    margin: 10px 0;
  }
  </style> 